//
//  MyStockListController.m
//  Stock
//
//  Created by blacksun on 11-6-16.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "RadarSettingListController.h"
#import "StockRadarEditControll.h"
#import "StockAppHelper.h"


@implementation RadarSettingListController
@synthesize tableView;
@synthesize localStocks;
@synthesize updateTimer;
@synthesize timerCallback;
@synthesize updateSuccessNotification;
@synthesize myStockService; 
@synthesize remoteStocks;
@synthesize leftButton;
@synthesize rightButton;
@synthesize doneButton;
@synthesize localRadars;
@synthesize wantDeleteRadars;


-(void)didClikedAddButton;{
    StockRadarEditControll *radarEditController = [[StockRadarEditControll alloc] initWithNibName:@"StockRadarEditControll" bundle:nil];
    radarEditController.localRadars = self.localRadars;
    radarEditController.localStocks = self.localStocks;
    [self.navigationController pushViewController:radarEditController animated:YES];
    [radarEditController release];
    
}

-(void) didClikedDoneButton{
    [self.navigationItem setRightBarButtonItem:self.rightButton animated:YES];
    [self.navigationItem setLeftBarButtonItem:nil];
    [self.tableView setEditing:NO animated:YES];
    if (wantDeleteRadars.count>0) {
        [myStockService deleteStockRadars:wantDeleteRadars];
    }
}
-(void) didClikedEditButton{
    [self.navigationItem setLeftBarButtonItem:self.leftButton animated:YES];
    [self.navigationItem setRightBarButtonItem:self.doneButton animated:YES];
    [self.tableView setEditing:YES animated:YES];
    
}

-(void)requestFinishedWithResult:(id)aResult andUserinfo:(NSDictionary *)aUserinfo{
    NSString *action = [aUserinfo objectForKey:kASIHttpRequestUserinfoKey];
    if ([kMyStockServiceUpdateStock isEqualToString:action]) {//update section
        self.remoteStocks = aResult;
        for (MyStock *oldStock in localStocks) {
            for (MyStock *newStock in remoteStocks) {
                if ([oldStock.uuid isEqualToString:newStock.uuid]) {
                    oldStock.lastClosingPrice = newStock.lastClosingPrice;
                    oldStock.name = newStock.name;
                    oldStock.uuid = newStock.uuid;
                    oldStock.openingPrice = newStock.openingPrice;
                    oldStock.closingPrice = newStock.closingPrice;
                    oldStock.changedPrice = newStock.changedPrice;
                    oldStock.changedRate = newStock.changedRate;
                    oldStock.turnover = newStock.turnover;
                    oldStock.turnoverMoney = newStock.turnoverMoney;
                    oldStock.tc = newStock.tc;
                    oldStock.minPrice = newStock.minPrice;
                    oldStock.maxPrice = newStock.maxPrice;
                    oldStock.cnDifference = newStock.cn-oldStock.cn;
                    oldStock.cn = newStock.cn;
                    oldStock.crDifference = newStock.cr - oldStock.cr;
                    oldStock.cr = newStock.cr;
                    oldStock.prDifference = newStock.pr - oldStock.pr;
                    oldStock.pr = newStock.pr;
                    oldStock.mhDifference = newStock.mh - oldStock.mh;
                    oldStock.mh = newStock.mh;
                    oldStock.dateTime = newStock.dateTime;
                }
            }
        }
        [self.tableView reloadData];
        [self.myStockService batchAndAsynchronousSaveObjects:localStocks];
        [self.updateSuccessNotification postNotificationName:kUpdateSuccessNotification object:nil];
    }else if([kMyStockServiceDeleteStockRadar isEqualToString:action]){
        //[[StockAppHelper shareInstance] showAlertViewWithMessage:@"删除成功！" andDelegate:nil];
        [wantDeleteRadars makeObjectsPerformSelector:@selector(deleteObject)];
        [wantDeleteRadars removeAllObjects];
    }
}
-(void)requestFinishedwithError:(NSError *)aError andUserinfo:(NSDictionary *)aUserinfo{
    
}


-(void) updateLocalStocks{
    [self.myStockService updateMyStocks:localStocks];
}


- (void)dealloc
{
    [self.myStockService batchAndAsynchronousSaveObjects:localStocks];
    [self.myStockService cancleAllRequest];
    self.myStockService = nil;
    self.tableView = nil;
    [self.updateTimer invalidate];
    self.updateTimer = nil;
    self.timerCallback = nil;
    self.remoteStocks = nil;
    self.localStocks = nil;
    self.leftButton = nil;
    self.rightButton = nil;
    self.doneButton = nil;
    self.wantDeleteRadars = nil;
    [StockContext shareInstance].remoteMyStocks = nil;
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"阀值预警";
    //self.localStocks = [NSMutableArray array];
    self.updateSuccessNotification = [NSNotificationCenter defaultCenter];
    self.myStockService = [[[MyStockService alloc] initWithDelegate:self] autorelease];
    
    self.localStocks = [NSMutableArray arrayWithArray:[MyStock allObjects]];
    
    self.wantDeleteRadars = [NSMutableArray array];
    
    self.timerCallback = [[[TimerCallback alloc] initWithTarget:self action:@selector(updateLocalStocks)] autorelease];
    
    self.updateTimer = [NSTimer scheduledTimerWithTimeInterval:60 target:self.timerCallback selector:@selector(task) userInfo:nil repeats:YES];
    [self.navigationController setNavigationBarHidden:NO];
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    self.tableView.separatorColor = [UIColor grayColor];
    
    UIBarButtonItem *temp = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(didClikedAddButton)];
    self.leftButton = temp;
    [temp release];
    UIBarButtonItem *editButton = [[UIBarButtonItem alloc] initWithTitle:@"编辑" style:UIBarButtonItemStylePlain target:self action:@selector(didClikedEditButton)];
    self.rightButton = editButton;
    [self.navigationItem setRightBarButtonItem:editButton animated:YES];
    [editButton release];
    
    UIBarButtonItem *done = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(didClikedDoneButton)];
    self.doneButton = done;
    [done release];
    
    [self.myStockService updateMyStocks:localStocks];
    
    if (self.localRadars.count==0) {
        [self performSelector:@selector(didClikedAddButton) withObject:nil afterDelay:0.5];
    }
    
    //[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reciveDeleteStockNotification:) name:DeleteStockNotification object:nil];
    
}
/*
-(void)reciveDeleteStockNotification:(NSNotification *)notification{
    [self.localStocks removeAllObjects];
    [self.localStocks addObjectsFromArray:[MyStock allObjects]];
    [self.tableView performSelector:@selector(reloadData) withObject:nil afterDelay:0.3];
}*/

- (void)viewDidUnload{
    [super viewDidUnload];
    [self.myStockService batchAndAsynchronousSaveObjects:localStocks];
    [self.myStockService cancleAllRequest];
    [self.updateTimer invalidate];
    self.updateTimer = nil;
    self.timerCallback = nil;
    self.myStockService = nil;
    self.timerCallback = nil;
    self.tableView = nil;
    self.leftButton = nil;
    self.rightButton = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.tableView reloadData];
    
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    //[self.tableView reloadData];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.localRadars count];
}

- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        UIColor *clearColor = [UIColor clearColor];
        UIColor *whiteColor = [UIColor whiteColor];
        
        UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(10.0, 12.0, 70.0, 20.0)];
        nameLabel.backgroundColor = clearColor;
        nameLabel.textColor = whiteColor;
        nameLabel.tag = kStockNameTag;
        
        
        UILabel *todayPriceLabel = [[UILabel alloc] initWithFrame:CGRectMake(100.0, 12.0, 70.0, 20.0)];
        todayPriceLabel.backgroundColor = clearColor;
        todayPriceLabel.textColor = whiteColor;
        todayPriceLabel.tag = kStockTodayPriceTag;
        todayPriceLabel.textAlignment = UITextAlignmentRight;
        
        UIImageView *directionImage = [[UIImageView alloc] initWithFrame:CGRectMake(230, 4, 79, 37)];
        directionImage.tag = 864;
        
        
        UILabel *warningValue = [[UILabel alloc] initWithFrame:CGRectMake(230.0, 12.0, 70.0, 20.0)];
        warningValue.backgroundColor = clearColor;
        warningValue.textColor = whiteColor;
        warningValue.tag = kStockChangePriceTag;
        warningValue.textAlignment = UITextAlignmentRight;
        
        [cell.contentView addSubview:nameLabel];
        [cell.contentView addSubview:todayPriceLabel];
        [cell.contentView addSubview:directionImage];
        [cell.contentView addSubview:warningValue];
        
        [nameLabel release];
        [todayPriceLabel release];
        [directionImage release];
        [warningValue release];
        
    }
    NSInteger index = [indexPath row];
    NSString *imageName = @"cellbg1.png";
    if (index%2==1) {
        imageName = @"cellbg2.png";
    }
    cell.backgroundView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:imageName]] autorelease];
    
    UILabel *nameLabel = (UILabel *)[cell viewWithTag:kStockNameTag];
    //UILabel *todyLabel = (UILabel *)[cell viewWithTag:kStockTodayPriceTag];
    UILabel *warningLabel = (UILabel *)[cell viewWithTag:kStockChangePriceTag];
    
    StockRadar *radar = [localRadars objectAtIndex:index];
    NSArray *temp = [localStocks filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self.uuid=%@",radar.stockId]];
    MyStock *stock = temp.count>0?[temp objectAtIndex:0]:nil;
    nameLabel.text = stock.name;
    //todyLabel.text = [stock.closingPrice stringValue];
    warningLabel.text = radar.targetValue;
    
    NSString *accessoryImage = nil;
    if (radar.type == kStockMonitorTypeUp) {
        accessoryImage = @"up_arrow.png";
    }else{
        accessoryImage = @"down_arrow.png";
    }
    UIImageView *directImage = (UIImageView *)[cell viewWithTag:864];
    directImage.image = [UIImage imageNamed:accessoryImage];
    
    
    
    return cell;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}



// Override to support editing the table view.
- (void)tableView:(UITableView *)aTableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        StockRadar *currentRadar = [[localRadars objectAtIndex:indexPath.row] retain];
        [localRadars removeObject:currentRadar];
        [aTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];   
        [wantDeleteRadars addObject:currentRadar];
        [myStockService deleteStockRadars:wantDeleteRadars];
        [currentRadar release];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
/*- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewCellEditingStyleDelete;
}*/



@end
